Filter, Map and Reduce functions in Javascript




In this article, we shall see how to use the filter, map and reduce functions in javascript.

Filter function

The filter() function in javascript can be applied to an array, which iterates through the array and apply certain condition to the individual element. If the condition is satisfied then it will push the element to the output array else it will not add it to the output array.

Syntax

arr.filter(function callback(element, index, array) {
	// Check for condition and return true/false.
});
  

Example 1

Output

[ 45, 23, 21, 30 ]
  

In the above example, we have an array with the list of numbers. We apply the filter function to the 'numbers' array, and in the callback function we will receive each element in the array over each iteration to which the condition is applied. We have represented the callback function as arrow function with only the first parameter, which is enough for this scenario to filter the elements greater than 20.

Let's see another example to filter the employees array, whose salary is greater than 49000.

Output

[ { name: 'John', salary: 50000 }, { name: 'Paul', salary: 60000 } ]

Map function

The map() function is used to map the existing array and form a new array. The map() function in its callback function will contain the logic for transforming each elements of an array.

Syntax

var new_array = arr.map(function callback(element, index, array) {
    // Transformation logic and returns the element.
});

Example 1

In the above example, we have an array of numbers to which we apply map() function to get a new array containing the squares of each element in the array.

Let's see another example, which contains details of the employees in an array and we shall transform the names of the each employees to uppercase.

Example 2

Output

[
  { name: 'MARK', salary: 45000 },
  { name: 'JOHN', salary: 50000 },
  { name: 'PAUL', salary: 60000 }
]

Reduce function

The reduce() function is used to reduce the elements of an array to a single value. When reduce() function is applied to an array then it is applied to each elements of an array and the final output value will be obtained.

Syntax

arr.reduce(callback,initialValue);

The callback function will be called for each iteration in the array. The callback function will contain the following parameters.

accumulator - The return value of the previous iteration.

currentValue - The current element in the array.

index - Contains the index of the current element in the array.

array - This is array itself.

initialValue - This is an optional parameter which will act as the initial value of the accumulator value.

Example

Output

15

Most Read